The Merge Operator ( | ) Of Python Dictionary Class

Operator:

| (Merge Operator)

Overview:

  • The merge operator or the union operator combines the contents of the two dictionaries.
  • The resultant dictionary contains the union of two key spaces k1, k2 and their corresponding values from the dictionaries d1, d2 where d1 is the current dictionary(self, this and other similar names are used to refer to the first operand) on to which d2 is merged.
  • If both the dictionaries d1 and d2 have the same keys the key from d1 is taken for the merge operation.

Operands:

d1 - Current dictionary object

d2 - Another dictionary object

Return value:

The merged dictionary as a dict instance.

Example:

# Example Python program that applies the
# merge operator (|) to combine two
# Python dictionaries

# Dictionary 1
day1Price = {"t1":65,
             "t2":67,
             "t3":65,
             "t4":67.5,
             "t5":70};

# Dictionary 2
day2Price = {"t1":64.9,
             "t2":67.5,
             "t3":65,
             "t4":67.51,
             "t5":72,
             "t6":71};

# Merge the two dictionaries
union = day1Price | day2Price;
print(union);

Output:

{'t1': 64.9, 't2': 67.5, 't3': 65, 't4': 67.51, 't5': 72, 't6': 71}

 


Copyright 2023 © pythontic.com